<?php

namespace App\Http\Form;

use App\Models\WorkOrder\WorkOrderApplyContentModel;
use Illuminate\Support\Collection;

class AnalysisFormContent
{

    public WorkOrderApplyContentModel $model;

    public Collection $originalContent;

    public Collection $content;

    /**
     * @param string|WorkOrderApplyContentModel $workOrder
     */
    public function __construct($workOrder)
    {
        if ($workOrder instanceof WorkOrderApplyContentModel) {
            $this->model = $workOrder;
        } else {
            $this->model = WorkOrderApplyContentModel::query()->where("workOrderNo", $workOrder)->first();
        }
        $this->content = $this->originalContent = collect($this->model->content ? json_decode($this->model->content,
            true) : []);
        return $this;
    }


    /**
     * @return array
     */
    public function getContent(): array
    {
        return $this->content->toArray();
    }

    /**
     * 获取字段值
     *
     * @param string $field
     * @param mixed $defaultVal
     * @return mixed
     */
    public function getField(string $field, $defaultVal = "")
    {
        return $this->content->get($field, $defaultVal);
    }

    /**
     * 保存字段值
     *
     * @param string $field
     * @param $value
     */
    public function saveField(string $field, $value)
    {
        $this->model->update([
            "content"   => $this->originalContent->merge([$field => $value])->toJson(JSON_UNESCAPED_UNICODE),
            "updatedAt" => time()
        ]);
    }


    /**
     * @param array $mergedData
     * @return $this
     */
    public function mergeExtraContent(array $mergedData): AnalysisFormContent
    {
        $this->content = $this->content->merge($mergedData);
        return $this;
    }

    /**
     * @return Collection
     */
    public function toCollection(): Collection
    {
        return collect($this->content);
    }
}
